/*
 * @Author: 徐汉卿 xuhanqing@imohoo.com
 * @Date: 2023-07-18 17:19:24
 * @LastEditors: 徐汉卿 xuhanqing@imohoo.com
 * @LastEditTime: 2023-07-24 16:33:22
 * @FilePath: /sy-app2/src/store/user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import Taro from "@tarojs/taro";
import httpService from "@/service/httpService";
import { defineStore } from "pinia";
import { Router } from "tarojs-router-next";

export const useUserStore = defineStore({
  id: "userStore",
  state: () => ({
    token: undefined,
    userInfo: null,
  }),
  getters: {
    getToken() {
      return this.token || Taro.getStorageSync("Token");
      return this.token

    },
    getUserInfo() {
      return this.userInfo;
    },
  },
  actions: {
    setToken(params) {
      this.token = params;
      Taro.setStorageSync("Token", params);
    },
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
    },
    /**
     * 拉取用户信息
     */
    async fetchUserInfo() {
      const userRes = await httpService.get("/api/User", {
        params: {
          fromModule: "Login",
        },
      });
      this.userInfo["roleCode"] = userRes.result[0].roleCode;
    },
    /**
     * 退出登录
     */
    async logout() {
      Taro.removeStorageSync("Token");
      this.token = undefined;
      Taro.reLaunch({
        url: "/pages/login/index",
      });
    },
    /**
     * 登录
     * @param loginData
     */
    async login(loginData) {
      console.log(loginData);
      const loginRes = await httpService
        .post("/login", {
          data: loginData,
        })
        .then(async (res) => {
          // 登录跳转到首页
          // Router.toIndex();
  


          Taro.reLaunch({
            url: "/pages/index/index",
          });
          return res;
        });
        


          // 设置Token
    console.log('loginRes.result.token',loginRes);
    this.setToken(loginRes.result.token);
    // 存储登录用户的信息

    let userInfo = {
      userId: loginRes.result.userId,
      depaId: loginRes.result.depaId,
      userName: loginRes.result.userName,
      deptName: loginRes.result.depaName,
      roleName: loginRes.result.roleName,
    };

    // 设置用户信息
    this.setUserInfo(userInfo);
    console.log("登录状态存储处理");
    // 获取用户权限信息
    await this.fetchUserInfo();
    },
  },
});
